<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增出售记录')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:insert="include :: select2-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-record-add">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">购买账户：</label>
                <div class="col-sm-8">
                    <div class="input-group" style="width: 100%">
                        <select name="account" id="account" class="form-control m-b" >
                            <option value="1">账户1</option>
                            <option value="2">账户2</option>
                            <option value="3">账户3</option>
                            <option value="4">账户4</option>
                            <option value="5">账户5</option>
                            <option value="6">账户6</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">物品名称：</label>
                <div class="col-sm-8">
                    <select name="marketHashName" id="marketHashName" class="form-control m-b">
                        <option value=""></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售价格：</label>
                <div class="col-sm-8">
                    <input name="sellPrice" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售数量：</label>
                <div class="col-sm-8">
                    <input name="quantity" class="form-control" type="text" min="1" placeholder="请输入出售数量"
                           required>
                    <small class="form-text text-muted help-text" style="display: none;">
                    </small>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售平台：</label>
                <div class="col-sm-8">
                    <div class="col-sm-8">
                        <select class="form-control" name="platform" required>
                            <option value="1">悠悠有品</option>
                            <option value="2">BUFF</option>
                            <option value="3">C5Game</option>
                            <option value="4">Steam</option>
                            <option value="5">IGXE</option>
                            <option value="6">ECO</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:insert="include :: select2-js"/>
<script th:inline="javascript">
    var prefix = ctx + "system/sales"
    $("#form-record-add").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            let $form = $('#form-record-add');

            // 获取表单数据并修改 price
            let formData = $form.serializeArray();
            let postData = {};

            // 将表单数据转换为对象
            formData.forEach(item => {
                postData[item.name] = item.value;
            });

            // 将 price 字段的值乘以 100
            if (postData.sellPrice !== undefined && postData.sellPrice !== null && postData.sellPrice !== '') {
                postData.sellPrice = Math.round(parseFloat(postData.sellPrice) * 100);
            }

            $.operate.save(prefix + "/add", postData);
        }
    }

    $("input[name='createdTime']").datetimepicker({
        format: "yyyy-mm-dd HH:mm:ss",
        minView: 0,
        autoclose: true,
        language: 'en'
    });

    $("input[name='updatedTime']").datetimepicker({
        format: "yyyy-mm-dd HH:mm:ss",
        minView: 0,
        autoclose: true,
        language: 'en'
    });

    $(document).ready(function () {
        const quantityInput = $('input[name="quantity"]');
        const helpText = $('.help-text');
        // 初始化 select2
        $('select[name="marketHashName"]').select2({
            placeholder: "请输入物品名称关键词", // 占位符
            allowClear: true, // 允许清空
            width: '100%',    // 宽度
            minimumInputLength: 0, // 开始搜索前所需的最小字符数
            ajax: {
                url: '/system/inventory/getAvailableForSaleName',
                dataType: 'json',
                type: "post",
                delay: 250, // 延迟毫秒数，减少请求频率
                page: 50,
                data: function (params) {
                    // 发送到服务器的参数
                    return {
                        name: params.term.split('').join('%'), // 用户输入的文本在 `params.term` 中
                        account: $('#account').val()
                    };
                },
                processResults: function (data) {
                    // 处理后端返回的数据，转换成 Select2 期望的格式
                    if (data.code === 0) {
                        var results = $.map(data.rows, function (item) {
                            return {
                                id: item.marketHashName,     // 选项的实际值（通常用于表单提交）
                                text: item.name     // 选项的显示文本
                            }
                        });
                        return {
                            results: results
                        };
                    } else {
                        return {results: []};
                    }
                },
                success: function (data) {
                    if (data.code === 0 && data.rows.length > 0) {
                        console.log(data)
                        const maxAvailableQuantity = data.rows[0].availableQuantity;
                        const maxQuantity = data.rows[0].quantity;
                        quantityInput.attr('max', maxAvailableQuantity);

                        // 显示提示信息
                        helpText.text(`最大可出售数量: ${maxAvailableQuantity} 库存总数量: ${maxQuantity}`,).show();

                        // 自动填充为最大值（可选）
                        quantityInput.val(maxAvailableQuantity);
                    } else {
                        helpText.text('获取库存数量失败').show();
                        quantityInput.attr('max', '');
                    }
                },
                error: function () {
                    helpText.text('请求失败，请重试').show();
                    quantityInput.attr('max', '');
                },
                complete: function () {
                    quantityInput.prop('disabled', false).removeAttr('placeholder');
                },
                cache: true
            },
        }).on('select2:open', function () {
            // 打开时触发空搜索
            var $search = $('.select2-search__field');
            $search.trigger('input');
        });
    });

    function on() {
        const nameSelect = document.getElementById('name');
        const selectedValue = nameSelect.value;
        const quantityInput = $('input[name="quantity"]');
        const helpText = $('.help-text');

        if (selectedValue) {
            quantityInput.prop('disabled', true).attr('placeholder', '加载可用数量...');

            $.ajax({
                url: '/system/inventory/getAvailableForSaleName',
                type: 'POST',
                data: {
                    name: selectedValue,
                    account: $('#account').val()
                },
                success: function (data) {
                    if (data.code === 0 && data.rows.length > 0) {
                        console.log(data)
                        const maxAvailableQuantity = data.rows[0].availableQuantity;
                        const maxQuantity = data.rows[0].quantity;
                        quantityInput.attr('max', maxAvailableQuantity);

                        // 显示提示信息
                        helpText.text(`最大可出售数量: ${maxAvailableQuantity} 库存总数量: ${maxQuantity}`,).show();

                        // 自动填充为最大值（可选）
                        quantityInput.val(maxAvailableQuantity);
                    } else {
                        helpText.text('获取库存数量失败').show();
                        quantityInput.attr('max', '');
                    }
                },
                error: function () {
                    helpText.text('请求失败，请重试').show();
                    quantityInput.attr('max', '');
                },
                complete: function () {
                    quantityInput.prop('disabled', false).removeAttr('placeholder');
                }
            });
        } else {
            quantityInput.attr('max', '');
            helpText.hide();
        }
    }


</script>
</body>
</html>